package com.ruyiadmin.springboot.common.components.core;

import com.ruyiadmin.springboot.common.beans.system.SystemConfig;
import com.ruyiadmin.springboot.common.exceptions.RuYiAdminCustomException;
import com.ruyiadmin.springboot.common.utils.core.RuYiRsaUtil;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * <p>
 * Token工具类
 * </p>
 *
 * @author RuYiAdmin
 * @since 2022-07-20
 */
@Component
@EnableConfigurationProperties({SystemConfig.class})
@RequiredArgsConstructor
public class RuYiTokenComponent {

    //region 工具类私有属性

    private final SystemConfig systemConfig;

    //endregion

    //region 获取用户Token

    /**
     * 获取用户Token
     *
     * @return 用户Token
     * @throws Exception 异常信息
     */
    public String getToken() throws Exception {

        //获取请求url,ip,httpMethod
        HttpServletRequest request = ((ServletRequestAttributes) Objects
                .requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();

        String token = request.getHeader("token");
        String tokenSalt = request.getHeader("ts");

        if (StringUtils.isEmpty(token) || StringUtils.isEmpty(tokenSalt)) {
            throw new RuYiAdminCustomException("token is invalid");
        }

        if (!StringUtils.isEmpty(token) && !StringUtils.isEmpty(tokenSalt)) {
            token = RuYiRsaUtil.decrypt(token, systemConfig.getRsaPrivateKey());
            token = token.replace("^" + tokenSalt, "");
        }

        return token;
    }

    //endregion

    //region 获取口令Salt

    /**
     * <p>
     * 获取用户口令Salt
     * </p>
     *
     * @return 用户Token
     */
    public String getSalt() {

        //获取请求url,ip,httpMethod
        HttpServletRequest request = ((ServletRequestAttributes) Objects
                .requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();

        String tokenSalt = request.getHeader("ts");

        if (StringUtils.isEmpty(tokenSalt)) {
            throw new RuYiAdminCustomException("token is invalid");
        }

        return tokenSalt;
    }

    //endregion

}
